package org.chen.wordwave.act;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.bean.ApiResponse;
import org.chen.wordwave.bean.Lesson;
import org.chen.wordwave.init.WordInit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class VideoPlay extends AppCompatActivity {

    private StandardGSYVideoPlayer videoPlayer;
    private OrientationUtils orientationUtils;
    private Long lessonId;
    private String lessonTitle;
    private String videoUrl;
    private String coverImageUrl;
    private ApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.video_play_act);

        apiService = ApiClient.getClient(this).create(ApiService.class);

        getIntentData();
        init();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        lessonId = intent.getLongExtra("lesson_id", 0L);
        lessonTitle = intent.getStringExtra("lesson_title");
        videoUrl = intent.getStringExtra("video_url");
        coverImageUrl = intent.getStringExtra("cover_image");

        // 如果有lesson_id但没有其他信息，从API获取详情
        if (lessonId > 0 && (videoUrl == null || videoUrl.isEmpty())) {
            loadLessonDetail();
        } else {
            setupVideoPlayer();
        }
    }

    private void loadLessonDetail() {
        Call<ApiResponse<Lesson>> call = apiService
                .getLessonDetail(lessonId);

        call.enqueue(new Callback<ApiResponse<Lesson>>() {
            @Override
            public void onResponse(Call<ApiResponse<Lesson>> call,
                                   Response<ApiResponse<Lesson>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Lesson> apiResponse = response.body();
                    if (apiResponse.isSuccess()) {
                        Lesson lesson = apiResponse.getData();
                        lessonTitle = lesson.getTitle();
                        videoUrl = lesson.getVideoUrl();
                        coverImageUrl = lesson.getCoverImage();

                        runOnUiThread(() -> setupVideoPlayer());
                    } else {
                        showError("获取课程详情失败: " + apiResponse.getMsg());
                    }
                } else {
                    showError("网络请求失败");
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Lesson>> call, Throwable t) {
                showError("网络错误: " + t.getMessage());
                // 使用默认视频URL
                videoUrl = WordInit.videoUrl;
                lessonTitle = getString(R.string.en_study);
                runOnUiThread(() -> setupVideoPlayer());
            }
        });
    }

    private void showError(String message) {
        runOnUiThread(() -> {
            // 使用你的Toast工具显示错误信息
            Log.e("VideoPlay", message);
        });
    }

    private void init() {
        try {
            videoPlayer = findViewById(R.id.detail_player);

            String source1 = WordInit.videoUrl;
            videoPlayer.setUp(source1, false, getString(R.string.en_study));

            // 增加封面
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageResource(R.drawable.lesson_bg);
            videoPlayer.setThumbImageView(imageView);

            // 增加title
            videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);

            // 设置返回键
            videoPlayer.getBackButton().setVisibility(View.VISIBLE);

            // 设置旋转
            orientationUtils = new OrientationUtils(this, videoPlayer);

            // 设置全屏按键功能, 这是使用的是选择屏幕，而不是全屏
            videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orientationUtils.resolveByClick();
                }
            });

            // 是否可以滑动调整
            videoPlayer.setIsTouchWiget(true);

            // 设置返回按键功能
            videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });

            videoPlayer.startPlayLogic();
        } catch (Exception e) {
            Log.e("VideoPlayer", "Initialization Error: ", e);
        }
    }

    private void setupVideoPlayer() {
        try {
            videoPlayer = findViewById(R.id.detail_player);

            // 使用从API获取的视频URL，如果没有则使用默认URL
            String sourceUrl = (videoUrl != null && !videoUrl.isEmpty()) ? videoUrl : WordInit.videoUrl;
            String title = (lessonTitle != null && !lessonTitle.isEmpty()) ? lessonTitle : getString(R.string.en_study);

            videoPlayer.setUp(sourceUrl, false, title);

            // 设置封面图
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            if (coverImageUrl != null && !coverImageUrl.isEmpty()) {
                // 使用Glide加载网络图片
                 Glide.with(this).load(coverImageUrl).into(imageView);
                // 暂时使用默认图片
//                imageView.setImageResource(R.drawable.lesson_bg);
            } else {
                imageView.setImageResource(R.drawable.lesson_bg);
            }

            videoPlayer.setThumbImageView(imageView);

            // 增加title
            videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);

            // 设置返回键
            videoPlayer.getBackButton().setVisibility(View.VISIBLE);

            // 设置旋转
            orientationUtils = new OrientationUtils(this, videoPlayer);

            // 设置全屏按键功能, 这是使用的是选择屏幕，而不是全屏
            videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orientationUtils.resolveByClick();
                }
            });

            // 是否可以滑动调整
            videoPlayer.setIsTouchWiget(true);

            // 设置返回按键功能
            videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });

            videoPlayer.startPlayLogic();
        } catch (Exception e) {
            Log.e("VideoPlayer", "Setup Error: ", e);
            showError("视频初始化失败");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }

    @Override
    public void onBackPressed() {
        //先返回正常状态
        if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            videoPlayer.getFullscreenButton().performClick();
            return;
        }
        //释放所有
        videoPlayer.setVideoAllCallBack(null);
        super.onBackPressed();
    }
}

